package br.com.openari.fretedroidbh;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class CalcularFrete extends Activity implements OnClickListener, Runnable{
	private Handler handler = new Handler();
	private ProgressDialog dialog;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        Button btCalcular = (Button)findViewById(R.id.btCalcular);
        btCalcular.setOnClickListener(this);    
        
    }

	@Override
	public void run() {
		EditText edtCep = (EditText)findViewById(R.id.edtCep);
		EditText edtPeso = (EditText)findViewById(R.id.edtPeso);
		EditText edtComprimento = (EditText)findViewById(R.id.edtComprimento);
		EditText edtAltura = (EditText)findViewById(R.id.edtAltura);
		EditText edtLargura = (EditText)findViewById(R.id.edtLargura);		
		
		try {
			
			Calcular calcular = new Calcular(edtCep.getText().toString(), edtComprimento.getText().toString(), edtPeso.getText().toString(), 
					edtAltura.getText().toString(), edtLargura.getText().toString());
			
			final Frete frete = calcular.calcularFrete();
			
			handler.post(new Runnable() {
				
				@Override
				public void run() {
					Log.i("#RESULTADO: ", "teste xml");				
				}
			});
			
			
		} catch (Exception e) {
			Log.e("#ERRO: ", e.getMessage(), e);
			
			Toast toast = Toast.makeText(this, "Erro ao calcular o frete. Confira os valores digitados.", Toast.LENGTH_LONG);
			toast.show();
			
		}finally{
			dialog.dismiss();
		}
		
		
	}

	@Override
	public void onClick(View v) {
		
		EditText edtComprimento = (EditText)findViewById(R.id.edtComprimento);
		EditText edtAltura = (EditText)findViewById(R.id.edtAltura);
		EditText edtLargura = (EditText)findViewById(R.id.edtLargura);	
		
		if(validarPesoTotal(edtComprimento.getText().toString(), edtLargura.getText().toString(), edtAltura.getText().toString())){
			
			dialog = ProgressDialog.show(this, "Calcular", "Calculando Frete", false, true);
			
			new Thread(this).start();
			
		}else{
			Toast toast = Toast.makeText(this, "A soma do comprimento + largura + altura não pode ser maior que 150.", Toast.LENGTH_LONG);
			toast.show();
		}
		
		
	}
	
	private Boolean validarPesoTotal(String comp, String larg, String alt){
		
		Double comprimento = Double.valueOf(comp);
		Double largura = Double.valueOf(larg);
		Double altura = Double.valueOf(alt);
		
		Double total = comprimento + largura + altura;
		
		if(total > 150)
			return false;
		
		return true;
	}
}